import 'package:flutter_im_demo/model/file_model.dart';
import 'package:flutter_im_demo/model/friend_model.dart';
import 'package:flutter_im_demo/model/message_model.dart';
import 'package:flutter_im_demo/model/user_info_model.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

final dbHelp = DbHelp();

const tableList = [
  UserInfoModel.createTableSQL,
  Friend.createTableSQL,
  Message.createTableSQL,
  FileModel.createTableSQL,
];

class DbHelp {
  factory DbHelp() => _getInstance();

  static DbHelp get instance => _getInstance();
  static DbHelp _instance;

  DbHelp._internal() {
    database = _openDb();
  }

  static DbHelp _getInstance() {
    if (_instance == null) {
      _instance = DbHelp._internal();
    }
    return _instance;
  }

  Future<Database> database;

  Future<Database> _openDb() async {
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'imchat.db');
//    await deleteDatabase(path); // 测试时 删除老的数据库
    return await openDatabase(path, version: 1, readOnly: false,
        onCreate: (Database db, int version) async {
      for (var tableSql in tableList) {
        await db.execute(tableSql);
      }
      
      await db.execute("CREATE INDEX message_comb_key ON ${Message.tableName} (combKey)");
    });
  }
}
